<template>
  <el-drawer title="导出订单" v-model="dialogVisible" size="40%">
    <el-form :model="form" ref="formRef" :rules="rules" label-width="80px">
      <el-form-item label="订单类型" prop="tab">
        <el-select v-model="form.tab" placeholder="订单类型" style="width: 50%">
          <el-option v-for="item in tabs" :key="item.key" :label="item.name" :value="item.key" />
        </el-select>
      </el-form-item>

      <el-form-item label="时间范围" prop="time">
        <el-date-picker v-model="form.time" type="daterange" range-separator="至"
          start-placeholder="开始时间" end-placeholder="结束时间" value-format="YYYY-MM-DD"/>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSubmit" :loading="loading">导出</el-button>
      </el-form-item>
    </el-form>
    
  </el-drawer>
  
</template>

<script setup>
  import { ref, reactive } from 'vue'
  import { exportOrderApi } from '@/api/order.js'

  const props = defineProps({ 
    tabs: Array
  })

  const dialogVisible = ref(false)
  const formRef = ref(null)
  const form = reactive({
    tab: null,
    time: ""
  })
  const rules = reactive({
    tab: [
      { required: true, message: '请选择订单类型', trigger: 'change' },
    ]
  })

  function open() {
    dialogVisible.value = true
  }

  function close() {
    dialogVisible.value = false
  }

  const loading = ref(false)
  function onSubmit() { 
    loading.value = true
    let starttime = null
    let endtime = null

    if(form.time && Array.isArray(form.time)) {
      starttime = form.time[0]
      endtime = form.time[1]
    }

    formRef.value.validate((valid) => {
      if(!valid) return
      exportOrderApi({
        tab: form.tab,
        starttime,
        endtime
      }).then((data) => {
        let url = window.URL.createObjectURL(new Blob([data]))  
        let link = document.createElement('a')
        link.style.display = 'none'
        link.href = url
        let filename = (new Date()).getTime() + '.xlsx'
        link.setAttribute('download', filename)
        document.body.appendChild(link)
        link.click()
        close()
      }).finally(() => loading.value = false)
    })
  }

  defineExpose({
    open
  })
</script>

<style scoped>
</style>
